<template>
  <div class="z-form-item">
    <div class="z-input-group">
      <slot></slot>
      <div class="z-label" :class="[outline ? 'z-outline' : '']">
        <span v-if="showLabel">
          {{ label }}
        </span>
      </div>
    </div>
    <div class="errors" v-for="(msg, index) of error" :key="index">
      {{ msg }}
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, PropType, toRefs } from "vue";
import { Rule } from "../validate";
import useField from "./useField";

export default defineComponent({
  name: "ZFormItem",
  props: {
    label: String,
    showLabel: {
      type: Boolean,
      default: true,
    },
    outline: Boolean,
    name: {
      type: String,
      required: true,
    },
    rule: {
      type: [Object, Array] as PropType<Rule>,
      default: () => ({}),
    },
  },
  setup(props) {
    //
    const { name, rule } = toRefs(props);
    const { error } = useField(name.value, rule.value);

    return {
      error,
    };
  },
});
</script>
<style>
.z-form-item {
  margin: 1rem 0;
}
.z-input-group {
  width: 100%;
  position: relative;
  padding: 0.5rem;
  display: flex;
}
.z-input-group > div.z-label {
  position: absolute;
  color: var(--neutral);
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0.5rem;
  pointer-events: none;
  border-bottom: 2px solid var(--base-300);
}
.z-input-group > div.z-outline {
  border: 2px solid var(--base-300);
  border-radius: 0.5rem;
  padding: 0.5rem;
}
.z-input-group > div.z-label > span {
  position: absolute;
  left: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  transition: 0.5s;
}
.z-input-group textarea ~ div.z-label > span,
.z-input-group div:has(input[type="checkbox"]) ~ div.z-label > span,
.z-input-group div:has(input[type="radio"]) ~ div.z-label > span,
.z-input-group input:focus ~ div.z-label > span,
.z-input-group input:valid ~ div.z-label > span {
  top: 0;
  left: calc(0.5rem + 4px);
  padding: 0 1rem;
  background: var(--base-100);
  border-left: 2px solid var(--primary);
  border-right: 2px solid var(--primary);
}
.z-input-group textarea ~ div.z-label,
.z-input-group div:has(input[type="checkbox"]) ~ div.z-label,
.z-input-group div:has(input[type="radio"]) ~ div.z-label,
.z-input-group input:focus ~ div.z-label,
.z-input-group input:valid ~ div.z-label {
  border-color: var(--primary);
}
.z-form-item .errors {
  margin-top: 0.5rem;
  font-size: 0.75rem;
  line-height: 1rem;
  color: var(--error);
}
</style>
